from sqlalchemy import Column, Integer, String, Float, Text, Boolean, ForeignKey, Table, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from database import Base
from typing import List

# 地标与路径的多对多关联表
landmark_route_association = Table(
    'landmark_route_association',
    Base.metadata,
    Column('landmark_id', Integer, ForeignKey('landmarks.id'), primary_key=True),
    Column('route_id', Integer, ForeignKey('routes.id'), primary_key=True)
)

# 管理员模型
class Admin(Base):
    __tablename__ = "admins"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True, nullable=False)
    email = Column(String(100), unique=True, index=True, nullable=True)
    full_name = Column(String(100), nullable=True)
    hashed_password = Column(String(255), nullable=False)
    disabled = Column(Boolean, default=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    # 关系
    landmarks = relationship("Landmark", back_populates="creator")
    routes = relationship("Route", back_populates="creator")

# 地标模型
class Landmark(Base):
    __tablename__ = "landmarks"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    lat = Column(Float, nullable=False)
    lng = Column(Float, nullable=False)
    summary = Column(String(255), nullable=False)
    details = Column(Text, nullable=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    # 时间字段
    time = Column(DateTime, nullable=True)  # 地标时间信息（时间戳）

    # 外键关系
    creator_id = Column(Integer, ForeignKey("admins.id"))

    # 关系
    creator = relationship("Admin", back_populates="landmarks")
    routes = relationship("Route", secondary=landmark_route_association, back_populates="landmarks")

    # 媒体资源 - 使用JSON格式存储
    media_json = Column(Text, default="[]")

    @property
    def media(self):
        import json
        try:
            return json.loads(self.media_json)
        except:
            return []

    @media.setter
    def media(self, value):
        import json
        self.media_json = json.dumps(value)

# 路径模型
class Route(Base):
    __tablename__ = "routes"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    # 外键关系
    creator_id = Column(Integer, ForeignKey("admins.id"))

    # 关系
    creator = relationship("Admin", back_populates="routes")
    landmarks = relationship("Landmark", secondary=landmark_route_association, back_populates="routes")
